//
//  SaleShoppingCart.m
//  WestAir
//
//  Created by s on 16/9/25.
//  Copyright © 2016年 Henry. All rights reserved.
//

#import "SaleShoppingCart.h"
#import "SalesRecords.h"
#import "Product.h"
#import "SalesRecordsContent.h"

@interface SaleShoppingCart ()<SalesRecodsDelegate>{



}

@property(nonatomic,strong)NSMutableDictionary *dicData;
@property (weak, nonatomic) IBOutlet UIView *viewTotal;

@end

@implementation SaleShoppingCart
@synthesize dicData;

- (void)viewDidLoad {
    
    
    [super viewDidLoad];
    
    [self  initData];
    
    
    
}

-(void)initData{
    
    [NetWork  getShoppingCart:[HangBanInfo  currentHangBan].shoppingCartID callBack:^(id result, NSError *error) {
       
        if (!error) {
            dicData=result;
            [self  caculateAllPrice];
            [self.mainTableView reloadData];
        }
        
        ;
    }];
   
    _btnSubMit.backgroundColor=NORMAL_BULUE_COLOR;
    VIEW_CORNER(_btnSubMit,22);
    VIEW_CORNER(_viewTotal, 4.0);
    
    
}

#pragma mark Tableview Deleget

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    
    NSInteger numberRow;
    
    if (section==0 ) {
         NSArray  *arrData=dicData[@"xianXiao"];
         numberRow= arrData.count?(arrData.count+1):0;
    
    }
    else if(section==1){
    
        NSArray  *arrData=dicData[@"ziTi"];
        numberRow= arrData.count?(arrData.count+1):0;
        ;
    }
    else{
    
        NSArray  *arrData=dicData[@"youGou"];
        numberRow= arrData.count?(arrData.count+1):0;

    }
    
    return numberRow;
    
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
   
    float  height;
    if (section==0 ) {
        NSArray  *arrData=dicData[@"xianXiao"];
        height= arrData.count?30:0;
        
    }
    else if(section==1){
        
        NSArray  *arrData=dicData[@"ziTi"];
        height= arrData.count?30:0;

    }
    else{
        
        NSArray  *arrData=dicData[@"youGou"];
        height= arrData.count?30:0;

        
    }
    return height;
}
- (nullable UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{

    UIView  *view=[[UIView  alloc]  initWithFrame:CGRectMake(0, 0, tableView.widthV, 30)];
    
    return view;
    

}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
   
    NSArray  *arrTitle=@[@"现销",@"自提",@"邮购"];
    NSArray  *arrKey=@[@"xianXiao",@"ziTi",@"youGou"];
    
    UITableViewCell  *cell;
    if (indexPath.row==0) {
        cell=[tableView dequeueReusableCellWithIdentifier:@"SalesRecords"];
        SalesRecords  *cellTem=(SalesRecords  *)cell;
        cellTem.SalesTitle.text=arrTitle[indexPath.section];
        cellTem.selectionStyle=UITableViewCellSelectionStyleNone;
        UIView  *viewCorler=[cell.contentView  viewWithTag:100];
        
        UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:CGRectMake(0, 0, SCREEN_WIDTH-20, viewCorler.heightV) byRoundingCorners:UIRectCornerTopLeft|UIRectCornerTopRight cornerRadii:CGSizeMake(5, 5)]; // UIRectCornerBottomRight通过这个设置
        
        CAShapeLayer *maskLayer = [CAShapeLayer layer];
        maskLayer.frame = CGRectMake(0, 0, SCREEN_WIDTH-20, viewCorler.heightV);
        maskLayer.path = maskPath.CGPath;
        
        viewCorler.layer.mask = maskLayer;
        
       return cell;
    }
    else{
    
        cell=[tableView dequeueReusableCellWithIdentifier:@"SalesRecordsContent"];
        SalesRecordsContent  *cellTem=(SalesRecordsContent  *)cell;
        cellTem.selectionStyle=UITableViewCellSelectionStyleNone;
        cellTem.selesDelegate=self;
        cellTem.indexPath=indexPath;
        
        Product  *product=dicData[arrKey[indexPath.section]][indexPath.row-1];
        NSArray  *arrKeyTem=dicData[arrKey[indexPath.section]];

        UIView  *viewline=[cell.contentView  viewWithTag:101];
        UIView  *viewCorler=[cell.contentView  viewWithTag:100];
        
        UIBezierPath *maskPath; // UIRectCornerBottomRight通过这个设置
        if (indexPath.row==arrKeyTem.count) {
            
            
          maskPath = [UIBezierPath bezierPathWithRoundedRect:CGRectMake(0, 0, SCREEN_WIDTH-20, viewCorler.heightV)  byRoundingCorners:UIRectCornerBottomLeft|UIRectCornerBottomRight cornerRadii:CGSizeMake(5, 5)]; //
            
            viewline.hidden=YES;
        }
        else{
            maskPath = [UIBezierPath bezierPathWithRoundedRect:CGRectMake(0, 0, SCREEN_WIDTH-20, viewCorler.heightV)  byRoundingCorners:UIRectCornerBottomLeft|UIRectCornerBottomRight cornerRadii:CGSizeMake(5,5)]; //
            

            viewline.hidden=NO;
        }
        CAShapeLayer *maskLayer = [CAShapeLayer layer];
        maskLayer.frame = CGRectMake(0, 0, SCREEN_WIDTH-20, viewCorler.heightV) ;
        maskLayer.path = maskPath.CGPath;
        
        viewCorler.layer.mask = maskLayer;
        
       

        cellTem.lableTitle.text=product.FName;
        
        cellTem.lableNum.text=[NSString stringWithFormat:@"X%ld",(long)product.FQty];
        cellTem.lablePrice.text=[NSString stringWithFormat:@"¥%.1f",product.FPrice];
        
        return cell;
    }
 
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (indexPath.row==0) {
        return   40;
    }
    else{
      
        return   50;
    
    }
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{

       return 3;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    

    if (indexPath.row!=0) {
        
        NSMutableArray  *arrData=dicData[[self getStrKey:indexPath.section]];
        Product  *product=arrData[indexPath.row-1];
        if ( [[HangBanInfo  currentHangBan].FSubmitSalOrder  isEqualToString:@"1"]) {
            [CMCCIOTTipsCenter showErrorWithStatus:@"订单已经提交"];
            return;
        }  ;
        [CMCCIOTTipsCenter  showAlertTextFieldTitle:@"选择数量" message:@"" andTFOne:nil andTFTwo:^(UITextField * _Nullable textField) {
            
            textField.text=[NSString stringWithFormat:@"%ld",(long)product.FQty];
            UIView  *leftView=[[UIView alloc]  initWithFrame:CGRectMake(0, 0, 10, 10)]          ;
            textField.leftView=leftView;
            textField.leftViewMode=UITextFieldViewModeAlways;
            textField.keyboardType=UIKeyboardTypeNumberPad ;

            
            ;
        } cancelTitle:@"取消" cancelBlock:^(CMCCIOTIGAlertActionCustomer * _Nullable action) {
            
            
            ;
        } quireTitle:@"确定" quireBlock:^(CMCCIOTIGAlertActionCustomer * _Nullable action) {
            UITextField  *textField=action.textFields[0];

            if (textField.text.length) {
                    if ([textField.text  integerValue]>0) {
                    [NetWork  modProduc:product.FEntryID
                                   FQty:[textField.text integerValue]
                               callBack:^(id result, NSError *error){
                                   
                                   if (!error) {
                                       [CMCCIOTTipsCenter showSuccessWithStatus:result[@"message"]];

                                       product.FQty=[textField.text  integerValue];
                                       [self  caculateAllPrice];
                                       ;
                                       [self.mainTableView reloadData];
                                       ;
                                   }
                                  
                                 
                               }];
                   
                }
            }
            
           
            
    
            
        }];

    }
    
}

- (IBAction)popBack:(id)sender {
    
    [self.navigationController  popViewControllerAnimated:YES];
    
}

- (IBAction)btnSubMit:(id)sender {
    
    if ( [[HangBanInfo  currentHangBan].FSubmitSalOrder  isEqualToString:@"1"]) {
        [CMCCIOTTipsCenter showErrorWithStatus:@"订单已经提交"];
        return;
    }  ;


    [NetWork   SubmitOrder:dicData callBack:^(id result, NSError *error) {
        ;
    
        if (!error ) {
            
            dicData=nil ;
            [HangBanInfo  currentHangBan].FSubmitSalOrder=@"1";
            [self.mainTableView reloadData];
            
            [CMCCIOTTipsCenter  showSuccessWithStatus:result[@"message"]];
            
            [self caculateAllPrice];


        }
        else if ([result[@"IsSuccess"]  integerValue]==-1){
        
           dicData=nil ;
            [HangBanInfo  currentHangBan].FSubmitSalOrder=@"1";
            [self.mainTableView reloadData];
             [self caculateAllPrice];
        }
        
    }];
}


-(NSString *)getDateOfyyyyMMdd:(NSDate *)inputDate{
    
    NSDateFormatter *outputFormatter = [[NSDateFormatter alloc] init];
    [outputFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSString *str = [outputFormatter stringFromDate:inputDate];
    return str;
    
    
}

#pragma mark saleRecord  delegate

-(void)deleteShop:(NSIndexPath  * )index{
    
    if ( [[HangBanInfo  currentHangBan].FSubmitSalOrder  isEqualToString:@"1"]) {
        [CMCCIOTTipsCenter showErrorWithStatus:@"订单已经提交"];
        return;
    }  ;
    NSMutableArray  *arrData=dicData[[self getStrKey:index.section]];
    Product  *product=arrData[index.row-1];
    

    [NetWork   delProduc:product.FEntryID callBack:^(id result, NSError *error) {
      
        if (!error) {
            NSString  *strKey=[self getStrKey:index.section];
            NSMutableArray  *arrDelete=[NSMutableArray  arrayWithArray: dicData[strKey]];
            [arrDelete  removeObjectAtIndex:index.row-1];
            [dicData  setObject:arrDelete forKey:strKey];
            [self  caculateAllPrice];
            [self.mainTableView reloadData];
        };
    }];
    
   
}


-(void)caculateAllPrice{


    NSArray  *arrXianXiao=dicData[@"xianXiao"];
    NSArray  *arrYouGou=dicData[@"youGou"];
    NSMutableArray  *arrAllData=[[NSMutableArray  alloc]  init];
    [arrAllData  addObjectsFromArray:arrXianXiao];
    [arrAllData  addObjectsFromArray:arrYouGou];

     __block  float  totalPrice=0.0;
    
    [arrAllData  enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        
        Product  *product=obj;
        float  priceDanJia=product.FPrice;
        NSInteger  num=product.FQty;
        
        totalPrice  +=num*priceDanJia;
        ;
    }];
    
    
    
    self.lablPriceTotal.text=
    [NSString stringWithFormat:@"¥%.1f",totalPrice];
    
}

-(NSString  *)getStrKey:(NSInteger)section{

    NSString  *strKey=@"";
    switch (section) {
        case 0:
            strKey=@"xianXiao";
            break;
        case 1:
            strKey=@"ziTi";
            break;
            
        case 2:
            strKey=@"youGou";
            break;
            
            
        default:
            break;
    }
    
    return strKey;

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



@end
